#! /usr/bin/env python
# -*- coding: utf-8 -*-

"""Quick-and-dirty 'make' tool for building tovid documentation."""

import os
import sys
import glob
import libtovid
from libtovid import gui
# Get mypydoc
import mypydoc

# Directories are relative to the docmake script
base_dir = os.path.dirname(sys.argv[0])

# Directory containing .t2t doc sources
source_dir = os.path.abspath(base_dir + '/src')
# Directory to save output in
dest_dir = os.path.abspath(base_dir + '/html')
man_dir = os.path.abspath(base_dir + '/man')
man_pages = ['todisc', 'tovid', 'idvid', 'makemenu', 'makedvd', \
    'pymakexml', 'makexml', 'postproc', 'todisc']

# Temporary directory to hold wikitext
wiki_dir = os.path.abspath(base_dir + '/wiki')

# Subdirectories of source_dir containing translations to build
translation_subdirs = ['en', 'es']


# Add full names of python modules to document with pydoc
pydoc_modules = []
mods = libtovid.__all__
for mod in mods:
    pydoc_modules.append('libtovid.%s' % mod)


def newer(source, target):
    """Return True if the source file is more recently modified than the
    target; False otherwise."""
    source_mod = os.path.getmtime(source)
    if os.path.exists(target):
        target_mod = os.path.getmtime(target)
    else:
        target_mod = 0

    return source_mod > target_mod

    
def generate_t2t_tarballs():
    """Create tar/gzip of all t2t sources in the html/download directory."""
    print "Generating .tar.gz of all .t2t sources..."
    for lang in translation_subdirs:
        cmd = 'tar --exclude .svn -czvvf tovid_t2t_%s.tar.gz src/%s' % \
                (lang, lang)
        os.system(cmd)
        print "Generated tovid_t2t_%s.tar.gz" % lang


def generate_manpages():
    for manpage in man_pages:
        infile = '%s/en/%s.t2t' % (source_dir, manpage)
        outfile = '%s/%s.1' % (man_dir, manpage)
        if newer(infile, outfile):
            generate_manpage(infile, outfile)
        else:
            print "Skipping %s" % outfile

def generate_manpage(t2tfile, manfile):
    print "Generating manual page from %s" % t2tfile
    cmd = 'txt2tags -t man -i "%s" -o "%s"' % (t2tfile, manfile)
    os.system(cmd)


def generate_pydocs():
    print "Generating HTML documentation of libtovid Python sources"
    for mod in pydoc_modules:
        print "Writing %s/pydocs/%s.html" % (dest_dir, mod)
        htmlfile = open("%s/pydocs/%s.html" % (dest_dir, mod), 'w')
        gen = mypydoc.HTMLGenerator()
        html = gen.document(mod)
        if html:
            htmlfile.write(html)
            htmlfile.close()
        else:
            print "Couldn't generate docs for %s" % mod
        # Run tidy on HTML output
        #os.popen2("tidy -utf8 -i -m %s" % htmlfile)


def generate_html(t2tfile, htmlfile):
    cmd = 'txt2tags -i %s -o %s' % (t2tfile, htmlfile)
    cmd += ' --encoding iso-8859-1'
    cmd += ' -t xhtml --css-sugar --toc --style=tovid_screen.css'
    # Run txt2tags cmd, displaying its normal output
    os.system(cmd)

    # Run tidy on HTML output
    #os.popen2("tidy -utf8 -i -m %s" % htmlfile)

    
def generate_all_html():
    print "Generating HTML for all translations of documentation."
    # Convert all language translations (.t2t sources) to HTML
    for trans_dir in translation_subdirs:
        print "Looking for .t2t sources in %s/%s" % (source_dir, trans_dir)
        for t2tfile in glob.glob('%s/%s/*.t2t' % (source_dir, trans_dir)):
            # Determine output path/filename
            # (Strip .t2t from basename and put in dest_dir/trans_dir)
            outfile = '%s/%s/%s.html' % \
                    (dest_dir, trans_dir, os.path.basename(t2tfile)[:-4])
            
            # If the .t2t source is newer than the existing HTML target,
            # recreate the HTML.
            if newer(t2tfile, outfile):
                print "Source file: %s is new. Regenerating %s" % \
                    (t2tfile, outfile)
                generate_html(t2tfile, outfile)
            else:
                print "Skipping file: %s" % t2tfile

if __name__ == '__main__':

    usage = "Usage: docmake [targets], where targets may be:\n"
    usage += "manpages, pydocs, tarballs, or html (or any combination)\n"

    print "tovid documentation maker"
    if len(sys.argv) < 2:
        print usage
        sys.exit()
    for arg in sys.argv[1:]:
        if arg == 'manpages':
            generate_manpages()
        elif arg == 'pydocs':
            generate_pydocs()
        elif arg == 'tarballs':
            generate_t2t_tarballs()
        elif arg == 'html':
            generate_all_html()
        else:
            print usage
            print "Unknown argument: %s" % arg

